package com.tz.crm.controller.system;

import com.tz.crm.entity.Department;
import com.tz.crm.entity.Role;
import com.tz.crm.entity.User;
import com.tz.crm.entity.enumeration.Gender;
import com.tz.crm.service.DepartmentService;
import com.tz.crm.service.RoleService;
import com.tz.crm.service.UserService;
import com.tz.crm.utils.DateUtil;
import com.tz.crm.utils.Pager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created by Administrator on 2017/3/15 0015.
 */
@Controller
@RequestMapping("/system/user")
public class UserController {

    @Resource
    UserService userService;
    @Resource
    DepartmentService departmentService;
    @Resource
    RoleService roleService;

    /*
     * 用户列表
     */
    @RequestMapping("/search")
    public String searchUser(Model model, Pager pager, User user) {
        Pager<User> pager1 = userService.getByPager(pager, user);
        model.addAttribute("pager", pager1);
        model.addAttribute("user", user);
        return "system/userList";
    }

    /**
     * 跳转到新增员工页面
     */
    @RequestMapping("/initAdd")
    public String initAdd(Model model) {
        List<Department> departments = departmentService.getAll();
        model.addAttribute("departments", departments);
        model.addAttribute("user", new com.tz.crm.entity.dto.User());
        return "system/addUser";
    }

    /**
     * 根据id查询员工信息,跳转到更新员工页面
     */
    @RequestMapping("/initUpdate")
    public String getById(String id, Model model) {
        List<Department> departments = departmentService.getAll();
        model.addAttribute("departments", departments);
        User u = userService.get(id);
        //封装成dto
        com.tz.crm.entity.dto.User user = new com.tz.crm.entity.dto.User();

        user.setEmpNo(u.getEmpNo());
        user.setRealName(u.getRealName());
        user.setTelephone(u.getTelephone());
        user.setRemarks(u.getRemarks());
        user.setBirthDate(DateUtil.format(u.getBirthDate(), "yyyy-mm-dd"));
        user.setDeptId(u.getDept().getId());
        user.setGender(u.getGender());
        user.setValid(u.isValid());
        user.setMaxCustomer(u.getMaxCustomer());
        user.setUsername(u.getUsername());

        String roleIds = "";
        String roleNames = "";
        List<Role> roles = userService.getRoleListByUserId(id);
        for (Role role : roles) {
            String roleId = role.getId();
            String roleName = role.getName();
            roleIds += (roleId + ",");
            roleNames += (roleName + ",");
        }
        user.setRoleIds(roleIds.substring(0, roleIds.length() - 1));
        user.setRoleNames(roleNames.substring(0, roleNames.length() - 1));
        model.addAttribute("user", user);
        model.addAttribute("userId",id);
        return "system/updateUser";
    }

    /**
     * 新增/更新  员工
     */
    @RequestMapping("/addOrUpdate/*")
    public String addUser(@Validated com.tz.crm.entity.dto.User user, BindingResult bindingResult,String userId,
                          Model model, String userGender, String deptId, String userValid, HttpServletRequest request) {
        if (bindingResult.hasErrors()) {
            model.addAttribute("user", user);
            return "system/addUser";
        } else {
            User u = new User();
            if (departmentService.getById(deptId) != null) {
                u.setDept(departmentService.getById(deptId));
            }
            u.setGender("MALE".equals(userGender) ? Gender.MALE : Gender.FEMALE);
            u.setValid("true".equals(userValid) ? true : false);

            u.setRealName(user.getRealName());
            u.setBirthDate(DateUtil.parse(user.getBirthDate(), "yyyy-mm-dd"));
//            u.setMaxCustomer(Integer.parseInt(user.getMaxCustomer()));
            u.setMaxCustomer(user.getMaxCustomer());
            u.setEmpNo(user.getEmpNo());
            u.setUsername(user.getUsername());
            u.setRemarks(user.getRemarks());
            u.setTelephone(user.getTelephone());

            String roleIds = user.getRoleIds();

            if (request.getRequestURI().endsWith("add")) {
                userService.saveWithRole(u,roleIds);
            } else if (request.getRequestURI().endsWith("update")) {
                u.setId(userId);
                userService.updateWithRole(u,roleIds);
            }
            return "redirect:/system/user/search";
        }
    }

    /**
     * 角色列表
     */
    @RequestMapping("/initRoleList")
    public String initRoles(Model model) {
        List<Role> roles = roleService.getAll();
        model.addAttribute("roles", roles);
        return "system/selectRoles";
    }
}
